const jwt = require('jsonwebtoken')

function sign(option) {
  // sign用于生成token，666作为加密的私钥可以自行定义
  return jwt.sign(option, '666', {
    expiresIn: '1h'
  })
}

let verify = (isAdmin) => {
  return async (ctx, next) => {
    let jwtToken = ctx.req.headers.authorization
    if (jwtToken) {
      try {
        let decoded = jwt.verify(jwtToken, '666');
        ctx.state.user = decoded; // 将解析出的用户信息绑定到请求对象的ctx.state中
        if (isAdmin) {
          let { admin } = decoded;
          if (admin) {
            await next();
          } else {
            ctx.status = 401;
            ctx.body = {
              code: 1,
              message: '你不是管理员！权限不够'
            };
          }
        } else {
          await next();
        }
      } catch (err) {
        ctx.status = 401;
        ctx.body = {
          code: 1,
          message: 'token失效'
        };
      }
    } else {
      ctx.status = 401;
      ctx.body = {
        code: 1,
        message: '请提供token'
      };
    }
  };
};

module.exports = {
  sign,
  verify
}